package com.mediacloud.app.newsmodule.activity.audio

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.flyco.tablayout.listener.OnTabSelectListener
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.assembly.util.*
import com.mediacloud.app.assembly.views.BlurTransformation2
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.ReadDataReciver
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.video.VideoAlbumIntroduceFragment
import com.mediacloud.app.newsmodule.fragment.PagerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.newsmodule.utils.spider.FollowKit
import com.mediacloud.app.newsmodule.utils.spider.IAttentionCall
import com.mediacloud.app.quanzi.model.BaseDataBean
import com.mediacloud.app.reslib.analysis.AnalysisUtils
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.util.ClickUtils
import com.tencent.liteav.demo.superplayer.model.entity.AlbumDetail
import com.utils.UriTool
import kotlinx.android.synthetic.main.activity_audio_album_detail_.*
import kotlinx.android.synthetic.main.layout_broccoli2.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 音频专辑 appfactory://${this.templateConf.androidPKG}/type35?articleid=xxx
 */
class AudioAlbumDetailActivity : BaseBackActivity() {
    val titles: MutableList<String> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogItem: CatalogItem? = null
    var articleItem: ArticleItem? = null
    var spiderCmsApi: SpiderCmsApi.ISpiderCmsApi? = null
   // var shareWarp: ShareWrap? = null
    var data: AlbumDetail? = null
    var componentTitle:String?= null
    override fun getLayoutResID(): Int {
        return R.layout.activity_audio_album_detail_
    }

    override fun showTitleBar() = false

    override fun getFitSystemWindow() = false


    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val uriData = intent.data
        if (uriData != null) {
            isFromH5OpenToReStart = UriTool.isFromH5OpenToReStart(this, uriData);
            val articleid: String? =
                uriData.getQueryParameter("articleid")
            val title = uriData.getQueryParameter("title")
            val cname = uriData.getQueryParameter("cname")
            catalogItem = CatalogItem()
            catalogItem?.catname = cname
            articleItem = ArticleItem()
            try {
                articleItem?.title = title
                articleItem?.id = articleid?.toLong() ?: 0
            } catch (e: Exception) {
            }
        } else {
            articleItem = intent.getParcelableExtra("data")
            catalogItem = intent.getParcelableExtra("catalog")
        }
        componentTitle = intent.getStringExtra("title")

        spiderCmsApi = SpiderCmsApi.getSpiderCmsApi(this)
        val imgBack = findViewById<View>(R.id.backIv)
        imgBack.setOnClickListener {
            ClickUtils.delayClickable(it)
            finish()
        }
        dealStatusBar(imgBack)

        getDetail()
        readStatus()
//        shareWarp = ShareWrap(this, false)
//        shareWarp?.setShowFunction(true)

//        val linkedHashSet = AppFactoryGlobalConfig.getAppServerConfigInfo(this)?.newsDetailConfig?.linkedHashSet
//        linkedHashSet?.let {
//            if (!it.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !it.contains(NewsDetailStyleConfig.SHARE_BUTTON)) {
//                shareIv.visibility = View.GONE
//            }else{
//                shareIv.visibility = View.VISIBLE
//            }
//        }
//        shareIv.setOnClickListener {
//            ClickUtils.delayClickable(it)
//            shareWarp?.show(mRootView, false, true, false)
//        }
        StatusBarUtil.setDarkMode(this)

    }

    private fun dealStatusBar(imgBack: View) {
        val params = imgBack.layoutParams as ConstraintLayout.LayoutParams
        params.topMargin = params.topMargin.coerceAtLeast(StatusBarUtil.getStatusBarHeight(this))
        imgBack.layoutParams = params
    }


    private fun getDetail() {
        spiderCmsApi?.getAlbumArticleDetail("${articleItem?.getId()}")?.enqueue(object :
            Callback<BaseDataBean<AlbumDetail>> {
            override fun onFailure(call: Call<BaseDataBean<AlbumDetail>>, t: Throwable) {
                if (isFinishing || isDestroyed) {
                    return
                }
                toast(getString(R.string.net_not_give_force))
            }

            override fun onResponse(call: Call<BaseDataBean<AlbumDetail>>, response: Response<BaseDataBean<AlbumDetail>>) {
                if (isFinishing || isDestroyed) {
                    return
                }
                var result: BaseDataBean<AlbumDetail>? = response.body()
                if (result?.state == 200) {
                    result?.data?.let {
                        broccoliLayout.visibility = View.GONE
                        setUi(it)
                    }

                }
            }
        })
    }


    private fun readStatus() {
        val readStatusInvoker = ReadStatusInvoker(object : DataInvokeCallBack<ReadDataReciver> {
            override fun success(data: ReadDataReciver) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(applicationContext, articleItem, data.virtualIncrement)
            }

            override fun fault(data: Any) {
                if (isFinishing || isDestroyed) {
                    return
                }
                AnalysisUtils.readsAnalysis(
                    applicationContext,
                    articleItem,
                    AnalysisUtils.DefaultVirtualIncrement
                )
            }
        })
        readStatusInvoker.readStatistics("${articleItem?.getId()}", 1)
    }

    /**
     * 关注
     */
    private fun attention(spiderId: String?) {
        if (spiderId == null) return
        view.isClickable = false

//        FollowKit.followOrNot(null,this, spiderId, articleItem?.spider_user?.userNickName, object : IAttentionCall {
//            override fun onAttentionResult(attention: Boolean) {
//                if (isFinishing || isDestroyed) {
//                    return
//                }
//                view.isClickable = true
//
//            }
//
//            override fun onAttentionFail() {
//                if (isFinishing || isDestroyed) {
//                    return
//                }
//                view.isClickable = true
//            }
//        }, articleItem,attentionTv)
    }


    @SuppressLint("SetTextI18n")
    private fun setUi(data: AlbumDetail?) {
        this.data = data
        articleItem?.url = data?.shareUrl
        articleItem?.title = data?.title
     //   shareWarp?.init(articleItem, catalogItem)
//        attentionTv.setOnClickListener {
//            ClickUtils.delayClickable(it)
//            if (UserInfo.isLogin(this)) {
//                if (TextUtils.isEmpty(data?.authorId)) {
//                    ToastUtil.showToast(this, resources.getString(R.string.sub_fail), R.drawable.attention_failed)
//                    return@setOnClickListener
//                }
//                attention("${data?.authorId}")
//            } else {
//                LoginUtils.request_source=LoginUtils.source_follow;
//                LoginUtils.invokeLogin(this)
//            }
//        }
        data?.let {

            albumTitleTv.text = it.title
            val logo = /*if (!TextUtils.isEmpty(data.backgroundColor)) {
                data.backgroundImage
            } else {*/
                data.imagePath
            //  }
            articleItem?.logo = logo

            albumLogoIv.load(logo, 0, null)
            val option = RequestOptions()
                .transform(BlurTransformation2(this))

            Glide.with(this).load(logo).apply(option).into(backGroundIv)
            introTv.text = it.summary
            titles.add("选集")
            titles.add("介绍")
            val f = AudioAlbumListFragment()
            val b = Bundle()
            b.putString("AlbumId", it.albumId)
            b.putString("collectionName", it.title)
            b.putString("contentColumn", catalogItem?.catname)
            b.putBoolean("isFollowed", it.isFollowed)
            f.arguments = b
            fragments.add(f)

            val f2 = VideoAlbumIntroduceFragment()
            val b2 = Bundle()
            b2.putString("Intro", it.summary)
            f2.arguments = b2
            fragments.add(f2)
            adapter = PagerAdapter(fragments, titles, supportFragmentManager)
            viewPager.adapter = adapter
            tabLayout.setViewPager(viewPager)

            viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                }

                override fun onPageSelected(position: Int) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    //   slidebackLayout.scrollView = (fragments[position] as IScrollView).getScrollView()
                }

                override fun onPageScrollStateChanged(state: Int) {

                }
            })

            tabLayout.getTitleView(0).setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
            tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
                override fun onTabSelect(position: Int) {
                    titles.forEachIndexed { index, _ ->
                        if (index == position)
                            tabLayout.getTitleView(position).setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
                        else
                            tabLayout.getTitleView(index).setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)

                    }
                }

                override fun onTabReselect(position: Int) {
                }

            })
        }
    }
}